﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HZ.MBSM.DBUtility;

public partial class Supervise_TraStockList : System.Web.UI.Page, HZ.MBSM.BLL.TraDes
{
    public string _strUserType = "", _AreaId = "", _strAccountId = "", _strEndDate = "", _strStartDate = "", _strDisplay = "", _strParameter = "";
    private string DGJE = "", DHJE = "", bidprice = "", bakeprice = "", Nolimtprice = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        string strSql, _strEndDate = "", _strStartDate = "", _SortId = "",
                _strHospitalName;
        if (HZ.MBSM.BLL.Login.CheckAssert(this.UseAccountType))
        {

            HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
            if (_Account != null)
            {
                _AreaId = SysFun.ToTrim(_Account.AreaId);
                _strUserType = SysFun.ToTrim(_Account.Type);
                _strAccountId = SysFun.ToTrim(_Account.AccountId);
                _strHospitalName = SysFun.ToTrim(_Account.AccountName);

                //如果当前使用人是配送企业
                if (_strUserType == "2")
                {
                    chkUserPS.Visible = false;
                    lab1.Visible = false;

                    _AreaId = "530000";
                }

            }

            if (_strUserType == "3")
            {
                chkUserYY.Visible = false;
                _strDisplay = "none";
                //如果当前用户是医院，那么就把地区隐藏
                labArea.Visible = false;
                Label1.Visible = false;
            }
            else
            {
                chkUserYY.Visible = true;
                _strDisplay = "block";
                //如果是监督机构或中介就根据其所在的地区来选择
                //如果是省一级的监督机构就可以看到整个云南省的信息,如果是某个市的监督机构就只能看到本市的信息
                System.Text.StringBuilder strHtml = new System.Text.StringBuilder();
                string _strAreaNameForm, _strAreaIdForm;
                _strAreaNameForm = SysFun.IsSQL(SysFun.ToTrim(Request.Form["txtAreaName"]));
                _strAreaIdForm = SysFun.IsSQL(SysFun.ToTrim(Request.Form["txtAreaId"]));
                if (_strAreaNameForm != "" && _strAreaIdForm != "")
                {
                    strHtml.Append("<input type='text' name='txtAreaName' value ='" + _strAreaNameForm + "' id='Text1' language='javascript' onclick='return Text1_onclick()'  InvertedComma='所属地区' readonly />");
                    strHtml.Append("<input type='text' name='txtAreaId'  value ='" + _strAreaIdForm + "' style='display: none' />");
                }
                else
                {
                    strHtml.Append("<input type='text' name='txtAreaName' id='Text1' language='javascript' onclick='return Text1_onclick()'  InvertedComma='所属地区' readonly />");
                    strHtml.Append("<input type='text' name='txtAreaId' style='display: none' />");
                }
                if (_AreaId != "")
                {
                    strHtml.Append("<a href='javascript:AreaSelect(" + _AreaId + ")'>选择地区</a>");
                }
                labArea.Text = strHtml.ToString();
                labArea.Visible = true;
                Label1.Visible = true;
            }

            if (!IsPostBack)
            {
                //<!--初始化统计时间
                int Year, Month, Day, DMonth, Year1;
                Year = DateTime.Now.Year;
                Year1 = Year;
                DMonth = DateTime.Now.Month;
                Month = DMonth - 1;
                if (Month == 0)
                {
                    Year1 -= 1;
                    Month = 12;
                }

                Day = DateTime.Now.Day;
                txtStartDate.Text = Year1.ToString() + "-" + Month.ToString() + "-01";
                txtEndDate.Text = Year.ToString() + "-" + DMonth.ToString() + "-01";

                _strEndDate = SysFun.ToTrim(Request.QueryString["EndDate"]);
                _strStartDate = SysFun.ToTrim(Request.QueryString["StartDate"]);
                if (_strEndDate != "")
                {
                    txtEndDate.Text = _strEndDate;
                }
                if (_strStartDate != "")
                {
                    txtStartDate.Text = _strStartDate;
                }
                //初始化统计时间-->

                Db DbProject = new Db();
                System.Data.IDataReader dr;
                //<!--初始化大类
                int i = 0;
                strSql = "select sortid,sortname from product_sort ";
                dr = DbProject.DataReader(strSql);
                while (dr.Read())
                {
                    lstSort.Items.Add(dr["sortname"].ToString());
                    lstSort.Items[i++].Value = dr["sortid"].ToString();
                }
                lstSort.DataBind();
                dr.Close();
                dr.Dispose();
                _SortId = SysFun.ToTrim(Request.QueryString["SortId"]);
                if (_SortId != "")
                {
                    lstSort.SelectedValue = _SortId;
                }
                //初始化大类-->
                DbProject.Close();

                if (Request.QueryString["deal"] != null && Request.QueryString["deal"] != "")
                {
                    switch (Request.QueryString["deal"].ToString())
                    {
                        case "未确认送货":
                            dealDrop.SelectedIndex = 0;
                            break;
                        case "送货中":
                            dealDrop.SelectedIndex = 1;
                            break;
                        case "已入库":
                            dealDrop.SelectedIndex = 2;
                            break;
                        case "无法配送":
                            dealDrop.SelectedIndex = 3;
                            break;
                        case "到期未送":
                            dealDrop.SelectedIndex = 4;
                            break;

                    }

                }
            }
            if (Request.Form["butSelectAll"] == "查看全部")
            {

                strSql = @" select AccountId_YY,HospitalName,UserCode_YY,BuyPlanId,PlanName,StartTime,EndTime,PurchasePlanDate,
                            convert(numeric(20,2),sum(GoodsNum*tradeprice)) as DGJE , convert(numeric(20,2),sum(inflownum*tradeprice)) as DHJE 
                            from tra_GoodsId where  {0}  group by AccountId_YY,HospitalName,UserCode_YY,BuyPlanId,PlanName,StartTime,EndTime,PurchasePlanDate order by DHJE DESC,BuyPlanId";
                string _strtempWhere = fctConditions();
                strSql = String.Format(strSql, _strtempWhere);
                Db db1 = new Db();
                System.Data.IDataReader dr;
                dr = db1.DataReader(strSql);
                GridView1.DataSource = dr;
                GridView1.DataBind();
                dr.Close();
                dr.Dispose();
                db1.Close();
            }
            else
            {
                showGridView();
            }
        }
    }

    protected void Button5_Click(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// 查询总共有多少页
    /// </summary>
    /// <returns></returns>
    /// <summary>
    /// 将数据绑定到GridView1
    /// </summary>
    /// <param name="PageIndex">转向第几页</param>
    public void showGridView()
    {

        string strConditions, _SelectField = "";
        //            _SelectField = @"area.areaid,area.AreaName, AccountId_YY,HospitalName,UserCode_YY,BuyPlanId,PlanName,StartTime,EndTime,PurchasePlanDate,
        //                            convert(numeric(20,2),sum(GoodsNum*tradeprice)) as DGJE , convert(numeric(20,2),sum(inflownum*tradeprice)) as DHJE ";
        strConditions = fctConditions();
        Db db = new Db();
        DbPage dbPage = new DbPage(db);
        if ((_AreaId == "530000") && ((SysFun.ToTrim(Request.Form["txtAreaId"]) == "530000") || (SysFun.ToTrim(Request.Form["txtAreaId"]) == "")))
        {
            _SelectField = @"area.areaid as areaid,area.AreaName as AreaName, AccountId_YY,HospitalName,UserCode_YY,BuyPlanId,PlanName,StartTime,EndTime,PurchasePlanDate,
                            convert(numeric(20,2),sum(GoodsNum*tradeprice)) as DGJE , convert(numeric(20,2),sum(inflownum*tradeprice)) as DHJE,case DealStatus  when 0 then '未确认送货' when 1 then '送货中' when 2 then '已入库' when 4 then '无法配送' when 5 then '到期未送' end as DealStatus ";
            dbPage.Table = "tra_GoodsId,area";                                               //要查询的表明
            dbPage.SelectFieldGroup = "area.areaid,area.AreaName,AccountId_YY,HospitalName,UserCode_YY,BuyPlanId,PlanName,StartTime,EndTime,PurchasePlanDate,DealStatus";
            dbPage.Key = "BuyPlanId";                                               //表的主键    
            dbPage.Where = strConditions;                                           //查询条件    
            dbPage.SelectField = _SelectField;//要显示的字段
            dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页   
            dbPage.PageSize = 30;                                                    //没有显示记录条数   
            dbPage.OrderBy = "areaid,AreaName,DHJE,BuyPlanId";                  //排序字段
            dbPage.OrderByIsDesc = false;
        }
        else
        {
            _SelectField = @"areaid,AreaName, AccountId_YY,HospitalName,UserCode_YY,BuyPlanId,PlanName,StartTime,EndTime,PurchasePlanDate,
                            convert(numeric(20,2),sum(GoodsNum*tradeprice)) as DGJE , convert(numeric(20,2),sum(inflownum*tradeprice)) as DHJE ,case DealStatus  when 0 then '未确认送货' when 1 then '送货中' when 2 then '已入库' when 4 then '无法配送' when 5 then '到期未送' end as DealStatus ";
            dbPage.Table = "tra_GoodsId";                                               //要查询的表明
            dbPage.SelectFieldGroup = "areaid,AreaName,AccountId_YY,HospitalName,UserCode_YY,BuyPlanId,PlanName,StartTime,EndTime,PurchasePlanDate,DealStatus";
            dbPage.Key = "BuyPlanId";                                               //表的主键    
            dbPage.Where = strConditions;                                           //查询条件    
            dbPage.SelectField = _SelectField;//要显示的字段
            dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页   
            dbPage.PageSize = 30;                                                    //没有显示记录条数   
            dbPage.OrderBy = "areaid,AreaName,DHJE,BuyPlanId";                  //排序字段
            dbPage.OrderByIsDesc = true;

        }
        dbPage.DGJE = "convert(numeric(20,2),sum(GoodsNum*TradePrice)) as DGJE";
        dbPage.DHJE = "convert(numeric(20,2),sum(inflownum*TradePrice)) as DHJE";
        dbPage.bidprice = "convert(numeric(20,2),sum(case when GoodsState=0 then inflownum*TradePrice else 0 end)) as bidprice";
        dbPage.bakeprice = "convert(numeric(20,2),sum(case when GoodsState=1 then inflownum*TradePrice else 0 end)) as bakeprice";
        dbPage.Nolimtprice = "convert(numeric(20,2),sum(case when GoodsState=2 then inflownum*TradePrice else 0 end)) as Nolimtprice";
        System.Data.IDataReader dr = dbPage.ExecuteReaderGroup(60);
        DGJE = dbPage.DGJE; DHJE = dbPage.DHJE; bidprice = dbPage.bidprice; bakeprice = dbPage.bakeprice; Nolimtprice = dbPage.Nolimtprice;
        GridView1.DataSource = dr;
        GridView1.DataBind();
        dr.Close();
        dr.Dispose();
        dbPage.Db.Close();
        db.Close();
        this.DbPageFlip1.DbPage = dbPage;//将数据传给控键
    }
    /// <summary>
    /// 生成查询条件
    /// </summary>
    /// <returns></returns>
    public string fctConditions()
    {

        string _strTemp = " DealStatus>=0 and DealStatus<>3 and", _strProductName, _GoodsId, _strBuyPlanId, _strPlanName, _strSortId = "", _strAreaIdForm = "", _strProductName_X;
        _strAreaIdForm = SysFun.ToTrim(Request.Form["txtAreaId"]);
        if ((_AreaId == "530000") && ((_strAreaIdForm == "530000") || (_strAreaIdForm == "")))
        {
            //_strTemp = " DealStatus=2 and LEFT(CONVERT(varchar(255), tra_GoodsId.AreaId), 4)+'00'=Area.AreaId and projectid=" + _projectid+" and";   07/09/11 马
            _strTemp += "  LEFT(CONVERT(varchar(255), tra_GoodsId.AreaId), 4)+'00'=Area.AreaId and";
        }
        else
        {
            //_strTemp = " DealStatus=2 and  projectid=" + _projectid + " and";   07/09/11 马
            //_strTemp = " DealStatus=2 and";
        }

        //通用名
        _strProductName = txtProductName.Text.ToString().Trim();
        if (_strProductName != "")
        {
            _strTemp += "  ( ProductName like '%" + _strProductName + "%' or Product_SpellingCode like '%" + _strProductName + "%' )  and";
            _strParameter += "&ProductName=" + _strProductName;
        }
        //通用名
        _strProductName_X = TextBox1.Text.Trim().Trim();
        if (_strProductName_X != "")
        {
            _strTemp += "  ( ProductName = '" + _strProductName_X + "' or Product_SpellingCode = '" + _strProductName_X + "' )  and";
            _strParameter += "&ProductName=" + _strProductName_X;
        }

        //商品流水号
        _GoodsId = txtGoodsId.Text.ToString().Trim();
        if (_GoodsId != "")
        {
            _strTemp += " GoodsId =" + _GoodsId + " and";
            _strParameter += "&GoodsId=" + _GoodsId;
        }


        //生产企业
        string _strAccountIdSC = SysFun.ToTrim(Request.Form["txtAccountIdSC"]);
        if (_strAccountIdSC != "" && chkUserSC.Checked == true)
        {
            _strTemp += " AccountId_SC =" + _strAccountIdSC + " and";
            _strParameter += "&AccountId_SC=" + _strAccountIdSC;
        }


        //中标企业
        string _strAccountIdZB = SysFun.ToTrim(Request.Form["txtAccountIdZB"]);
        if (_strAccountIdZB != "" && chkUserZB.Checked == true)
        {
            _strTemp += " AccountId_TB =" + _strAccountIdZB + " and";
            _strParameter += "&AccountId_TB=" + _strAccountIdZB;

        }


        //配送企业
        string _strAccountIdPS = SysFun.ToTrim(Request.Form["txtAccountIdPS"]);
        if (_strAccountIdPS != "" && chkUserPS.Checked == true)
        {
            _strTemp += " AccountId_PS =" + _strAccountIdPS + " and";
            _strParameter += "&AccountId_PS=" + _strAccountIdPS;
        }

        //要统计的时间范围
        _strEndDate = txtEndDate.Text.ToString();
        _strStartDate = txtStartDate.Text.ToString();
        if (_strEndDate != "" && _strStartDate != "")
        {
            _strTemp += " isnull(hospitalinflowdate,'3000-12-30') >='" + _strStartDate + "' and isnull(hospitalinflowdate,'1900-01-01') <='" + _strEndDate + "' and";
            _strParameter += "&EndDate=" + _strEndDate;
            _strParameter += "&StartDate=" + _strStartDate;
        }
        //采购单号
        _strBuyPlanId = txtBuyPlanId.Text.ToString().Trim();
        if (_strBuyPlanId != "")
        {
            _strTemp += " BuyPlanId like '%" + _strBuyPlanId + "%' and";
        }

        //采购单名称
        _strPlanName = txtPlanName.Text.ToString().Trim();
        if (_strPlanName != "")
        {
            _strTemp += "  PlanName like '%" + _strPlanName + "%' and";
        }

        //如果当前使用人是配送企业
        if (_strUserType == "2")
        {
            _strTemp += " AccountId_PS=" + _strAccountId + " and";
        }

        //根据登录人和地区确定医院范围
        if (_strUserType == "3")
        {
            _strTemp += "  AccountId_YY=" + _strAccountId + " and";
        }
        else
        {
            string _strAccountIdYY1 = SysFun.ToTrim(Request.Form["txtAccountIdYY"]);
            if (_strAccountIdYY1 != "" && chkUserYY.Checked == true)
            {
                _strTemp += " AccountId_YY =" + _strAccountIdYY1 + " and";
            }
            if ((_AreaId == "530000") && ((_strAreaIdForm == "530000") || (_strAreaIdForm == "")))
            {
                _strTemp += " tra_GoodsId.areaid>530000 And tra_GoodsId.areaid<419900 and";
            }
            else
            {

                if (_strAreaIdForm != "" && _strAreaIdForm != "530000")
                {
                    _AreaId = _strAreaIdForm;
                }
                _strTemp += SysFun.AreaIdWhere2(_AreaId);
            }
        }

        //药品类别
        _strSortId = lstSort.SelectedValue;
        if (_strSortId != "0")
        {
            _strTemp += " ( SortId=" + _strSortId + " or FrontSortId=" + _strSortId + " ) and";
            _strParameter += "&SortId=" + _strSortId;
        }
        //采购状态
        if (dealDrop.SelectedValue != "")
        {
            if (dealDrop.SelectedValue == "0")
            {
                _strTemp += " DealStatus=" + dealDrop.SelectedValue + " and buystatus=2 and";
            }
            else
            {
                _strTemp += " DealStatus=" + dealDrop.SelectedValue + " and";
            }
        }
        if (_strTemp != "")
        {
            _strTemp = "  " + _strTemp.Substring(0, _strTemp.Length - 3);
        }

        return _strTemp;

    }
    protected void ToEcxul_Click(object sender, EventArgs e)
    {
        string _strSql = "", _strAreaIdForm = "";
        Db db = new Db();
        System.Data.IDataReader dr;
        _strAreaIdForm = SysFun.ToTrim(Request.Form["txtAreaId"]);
        if ((_AreaId == "530000") && ((_strAreaIdForm == "530000") || (_strAreaIdForm == "")))
        {
            _strSql = "Select area.areaid,area.AreaName as 地区, BuyPlanId as 采购单号,UserCode_YY as 医院编码,HospitalName as 医院名称,PlanName as 采购单名称,StartTime as 开始时间,EndTime as 结束时间,PurchasePlanDate as 提交采购单时间,convert(numeric(20,2),sum(GoodsNum*tradeprice)) as '订货金额（元）' , convert(numeric(20,2),sum(inflownum*tradeprice)) as '送货金额（元）',case DealStatus  when 0 then '未确认送货' when 1 then '送货中' when 2 then '已入库' when 4 then '无法配送' when 5 then '到期未送' end as DealStatus  From tra_GoodsId,area Where     " + fctConditions() + "   Group By area.areaid,area.AreaName,AccountId_YY,HospitalName,UserCode_YY,BuyPlanId,PlanName,StartTime,EndTime,PurchasePlanDate,DealStatus Order By area.areaid,area.AreaName,'订货金额（元）' Desc,BuyPlanId Desc";
        }
        else
        {
            _strSql = "Select areaid,AreaName as 地区, BuyPlanId as 采购单号,UserCode_YY as 医院编码,HospitalName as 医院名称,PlanName as 采购单名称,StartTime as 开始时间,EndTime as 结束时间,PurchasePlanDate as 提交采购单时间,convert(numeric(20,2),sum(GoodsNum*tradeprice)) as '订货金额（元）' , convert(numeric(20,2),sum(inflownum*tradeprice)) as '送货金额（元）',case DealStatus  when 0 then '未确认送货' when 1 then '送货中' when 2 then '已入库' when 4 then '无法配送' when 5 then '到期未送' end as DealStatus  From tra_GoodsId Where     " + fctConditions() + "   Group By areaid,AreaName,AccountId_YY,HospitalName,UserCode_YY,BuyPlanId,PlanName,StartTime,EndTime,PurchasePlanDate,DealStatus Order By areaid,AreaName,'订货金额（元）' Desc,BuyPlanId Desc";
        }
        dr = db.DataReader(_strSql);
        this.GridView2.DataSource = dr;
        this.GridView2.DataBind();
        db.Close();
        dr.Close();
        dr.Dispose();
        SysFun.WriteToExcel(GridView2, this.Page, "按采购单查询.xls");


    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //OverRide　为了使导出成Excel可行！
    }
    #region TraDes 成员

    public string Name
    {
        get { return "按采购单查询"; }
    }

    public string Describe
    {
        get { return ""; }
    }

    public string ParentName
    {
        get { return "交易查询"; }
    }

    public System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> UseAccountType
    {
        get
        {
            System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> _AccountType = new System.Collections.Generic.List<HZ.MBSM.DAL.AccountType>();
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumHospitale);
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumAttorney);
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumSupervise);
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumCompany);
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumSuperviseChildCheck);
            return _AccountType;
        }
    }
    #endregion

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[0].Text = "合计";
            e.Row.Cells[1].Text = "";
            e.Row.Cells[2].Text = "";
            e.Row.Cells[3].Text = "";
            e.Row.Cells[4].Text = "";
            e.Row.Cells[5].Text = "";
            e.Row.Cells[6].Text = "";
            e.Row.Cells[7].Text = "";
            e.Row.Cells[8].Text = DGJE;
            e.Row.Cells[9].Text = DHJE;
            e.Row.Cells[10].Text = "";
        }
    }
}
